<?php

class Db_Helper
{

private static $_instance = null;      
private $pdo = null;
    
    private function __construct()
    {
        $this->pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME , DB_LOGIN ,  DB_PASSWORD);
        $this->pdo->query('SET_NAMES CP866');
    }
    
    /**
    * Запрет на клонирование
    * 
    */
    private function __clone() {}
    
    /**
    * Метод для вызова данного класса как singletone
    * 
    */
    
    public static function getInstance()
    {
        if( null == self::$_instance) { 
            self::$_instance = new Db_Helper();
        }
        return self::$_instance;
    }
    
    public function insert($sql)
    {
        //TODO placeholders
        $this->QueriesCount();
        return $this->pdo->prepare($sql)->execute();
    }
    
    public function update($sql)
    {
        $this->QueriesCount();
        return $this->pdo->prepare($sql)->execute();
    }
    
    public function select($sql)
    {
        $this->QueriesCount();
        $STH = $this->pdo->query($sql);
        if(!$STH){
            return false;
        }  
        $STH->setFetchMode(PDO::FETCH_ASSOC);
        return $STH->fetch();  
    }
    
    public function selectAll($sql, $modelName)
    {
        $this->QueriesCount();
        $STH = $this->pdo->query($sql);
        if(!$STH){
            return false;
        }  
        $STH->setFetchMode(PDO::FETCH_ASSOC);
        $n=0;
        while($row = $STH->fetch()) {  
            $arrayModels[$n] = new $modelName($row);
            $n++;   
        }
        if(isset($arrayModels)) {
            return $arrayModels;   
        } else {
            return false;
        }        
    }
    
    public function QueriesCount()
    {
        $_SESSION{'queryCount'}++;
    }
    
    public function closeDb()
    {
        if (null != $this->pdo){
            $this->pdo = null;
        }
    }    
}